<template>
  <div class="reset-password-container">
    <!-- 顶部背景 -->
    <div class="reset-password-header">
      <van-icon name="arrow-left" class="back-icon" @click="goBack" />
        <div class="welcome-text">重置密码</div>
    </div>

    <!-- 重置密码表单 -->
    <div class="reset-password-form">
      <!-- 手机号输入框 -->
      <div class="phone-input">
        <van-field
          v-model="formData.phone"
          placeholder="请输入手机号"
          class="input-field"
          :rules="[
            {
              required: true,
              pattern: /^1[3-9]\d{9}$/,
              message: '请输入正确的手机号',
            },
          ]"
          autocomplete="off"
        >
          <template #label>
            <div class="area-code" @click="goToCountrySelect">
              {{ selectedCountry.code }}
              <van-icon name="arrow-down" />
            </div>
          </template>
        </van-field>
      </div>

      <!-- 验证码输入框 -->
      <van-field
        v-model="formData.smsCode"
        center
        placeholder="请输入验证码"
        label=""
        class="input-field"
        autocomplete="off"
      >
        <template #button>
          <van-button
            size="small"
            class="send-code-btn"
            :disabled="countdown > 0"
            @click="sendCode"
          >
            {{ codeButtonText }}
          </van-button>
        </template>
      </van-field>

      <!-- 新密码输入框 -->
      <van-field
        v-model="formData.password"
        :type="showPassword ? 'text' : 'password'"
        placeholder="请输入新密码"
        class="input-field"
        :rules="[
          { required: true, message: '请输入新密码' },
          { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,20}$/, message: '密码必须包含大小写字母和数字，长度8-20位' }
        ]"
        autocomplete="off"
      >
        <template #right-icon>
          <van-icon
            :name="showPassword ? 'eye-o' : 'closed-eye'"
            @click="showPassword = !showPassword"
          />
        </template>
      </van-field>

      <!-- 重置密码按钮 -->
      <div class="reset-btn-wrapper">
        <van-button
          block
          class="reset-btn"
          :loading="loading"
          @click="handleReset"
        >
          重置密码
        </van-button>
      </div>
    </div>

    <!-- loading组件 -->
    <div v-if="loading" class="loading-wrapper">
      <van-loading type="spinner" color="#1989fa" size="40px" text="加载中..." vertical>加载中...</van-loading>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import url("./style/index.scss");
</style>

<script lang="ts" setup>
import { ref, reactive, onUnmounted } from "vue";
import { showToast } from "vant";
import { useRouter } from "vue-router";
import { resetPassword, sendSmsCode } from "@/api";
import countriesData from "@/data/countries.json";

// 定义国家类型
interface Country {
  name: string;
  code: string;
  countryCode: string;
  flag: string;
}

// 路由实例
const router = useRouter();

// 表单数据
const formData = reactive({
  phone: "",
  smsCode: "",
  password: "",
});

// 状态变量
const loading = ref(false);
const countdown = ref(0);
const codeButtonText = ref("获取验证码");
const showPassword = ref(false);
let timer: number | null = null;

// 国家选择相关
const countries = ref(countriesData);
const selectedCountry = ref(countries.value[0]); // 默认选择中国

// 返回上一页
const goBack = () => {
  router.back();
};

// 跳转到国家选择页面
const goToCountrySelect = () => {
  // 存储当前选中的国家代码到sessionStorage
  sessionStorage.setItem('selectedCountryCode', selectedCountry.value.countryCode);
  
  router.push({
    path: '/country-select',
    query: {
      from: 'reset-password'
    }
  });
};


// 发送验证码
const sendCode = async () => {
  // 如果正在倒计时中，直接返回
  if (countdown.value > 0) {
    return;
  }

  // 验证手机号
  if (!formData.phone) {
    showToast("请输入手机号");
    return;
  }
  
  // 根据选择的国家调整手机号验证规则
  if (selectedCountry.value.countryCode === 'CN' && !/^1[3-9]\d{9}$/.test(formData.phone)) {
    showToast("请输入正确的手机号");
    return;
  }

  try {
    // 调用发送验证码API
    const response = await sendSmsCode({ phone: formData.phone });
    
    if (response.code === 0) {
      // 开始倒计时
      countdown.value = 60;
      codeButtonText.value = `${countdown.value}s`;

      // 设置倒计时
      timer = window.setInterval(() => {
        countdown.value--;
        codeButtonText.value = `${countdown.value}s`;

        if (countdown.value <= 0) {
          clearInterval(timer as number);
          codeButtonText.value = "获取验证码";
          countdown.value = 0; // 确保倒计时重置为0
        }
      }, 1000);

      showToast({ type: "success", message: response.msg || "验证码已发送" });
    } else {
      showToast(response.msg || "发送验证码失败");
    }
  } catch (error) {
    console.error("发送验证码失败:", error);
    showToast("发送验证码失败，请稍后重试");
  }
};

// 处理重置密码
const handleReset = async () => {
  // 表单验证
  if (!formData.phone || !/^1[3-9]\d{9}$/.test(formData.phone)) {
    showToast("请输入正确的手机号");
    return;
  }

  if (!formData.smsCode) {
    showToast("请输入验证码");
    return;
  }

  if (!formData.password) {
    showToast("请输入新密码");
    return;
  }

  // 开始重置密码
  try {
    loading.value = true;

    // 调用重置密码API
    const response = await resetPassword({
      phone: formData.phone,
      smsCode: formData.smsCode,
      newPassword: formData.password,
    });

    // 检查返回结果
    if (response.code === 0) {
      showToast({ type: "success", message: "密码重置成功" });
      
      // 跳转到登录页面
      setTimeout(() => {
        router.push("/login");
      }, 1500);
    } else {
      showToast(response.msg || "密码重置失败");
    }
  } catch (error) {
    console.error("密码重置失败:", error);
    showToast("密码重置失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});
</script>